package org.grow.dealbill.service;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

/**
 * @Author: xwg
 * @CreateDate: 21-8-12
 */

@Service
public class CookieInterceptor  implements RequestInterceptor {

    public static String redisCookieName ="SESSION";
    public static String tomcatCookieName ="JSESSIONID";

    @Override
    public void apply(RequestTemplate requestTemplate) {
        ServletRequestAttributes requestAttributes =
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        Cookie[] cookies = request.getCookies();
        if (cookies ==null){
            return;
        }
        if (cookies.length==0){
            return;
        }
        for (int i = 0; i < cookies.length; i++) {
            if(cookies[i].getName().equals(redisCookieName)
                    || cookies[i].getName().equals(tomcatCookieName)){
                requestTemplate.header("Cookie",request.getHeader("Cookie"));
                break;
            };

        }


    }
}
